package com.ljt.security;

import com.ljt.exceptions.CaptchaException;
import com.ljt.response.ResultCode;
import com.ljt.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义验证码拦截器
 */
@Component("captchaFilter")
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取请求的URL
        String url = request.getRequestURI();
        // 验证请求方式是否为POST 并且请求的路径为login
        if (request.getMethod().equals("POST") && "/login".equals(url)) {
            try {
                // 验证验证码是否正确
                validate(request);
            } catch (CaptchaException e) {
                // 如果出现异常说明验证失败，交给认证失败处理器处理
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
            }
        }
        // 放行
        filterChain.doFilter(request,response);
    }

    public void validate(HttpServletRequest request) {
        // 获取传递的验证码
        String validateCode = request.getParameter("validateCode");
        System.out.println("validateCode = " + validateCode);
        // 获取传递的token令牌
        String token = request.getParameter("token");
        System.out.println("token = " + token);
        // 数据有效性验证
        if ("".equals(validateCode) || "".equals(token)) {

            throw new CaptchaException(ResultCode.CAPTCHA_VALIDATE_ERROR.getMessage());
        }
        // 验证token是否正确
        if (!validateCode.equals(redisUtil.hget("captcha", token))) {
            throw new CaptchaException(ResultCode.CAPTCHA_VALIDATE_ERROR.getMessage());
        }

        // 删除redis中存储的验证码
        redisUtil.hdel("captcha", token);
    }
}
